<?php
/**
 * 文件上传中心
 * @author chat
 * @version 1.0
 */
namespace app\common\library;

use app\common\exception\Upload as UploadException;
use Config;
use Env;

class Upload
{
	/**
	 * 上传配置
	 * @var null
	 */
	private static $config = null;

	/**
	 * 尺码对应表
	 * @var array
	 */
	private static $sizeChart = [
		'b'  => 0,
		'k'  => 1,
		'kb' => 1,
		'm'  => 2,
		'mb' => 2,
		'gb' => 3,
		'g'  => 3
	];

	/**
	 * 初始化相关数据
	 */
	private static function init()
	{
		if (is_null(self::$config)) {
			self::$config = Config::get('upload');
		}
	}

	/**
	 * 获取文件大小配置
	 */
	private static function getMaxSize(): int
	{
		$maxsize = Config::get('upload.maxsize');
		// 获取size
        preg_match('/(\d+)(\w+)/', $maxsize, $matches);
        $type = strtolower($matches[2]);

        $size = (int)$maxsize * pow(1024, isset(self::$sizeChart[$type]) ? self::$sizeChart[$type] : 0);
        return $size;
	}

	/**
	 * 上传图片
	 * @return 返回上传后的文件名供入库
	 */
	public static function image($file)
	{
		if (!$file) {
			return false;
		}

		$mimetype = Config::get('upload.mimetype');
		$path = Config::get('upload.path');

		$size = self::getMaxSize();
		$info = $file->validate(['size' => $size,'ext' => $mimetype])->move(Env::get('root_path') . 'public' . $path);
		if ($info) {
			return $info->getSaveName();
		} else {
			exception(UploadException::getErrorMsg(UploadException::E_UPLOAD_ERROR, $file->getError(), true), UploadException::E_UPLOAD_ERROR, '\\' . UploadException::class);
		}
	}
}
